package com.example.im.infra.executor.send.redis;

import com.example.im.infra.constant.ImConstants;
import com.example.im.infra.executor.send.AbstractBaseSendExecutor;
import com.example.im.infra.executor.send.dto.MessageInfo;
import com.example.im.infra.executor.send.dto.ScopeOfSendingEnum;
import com.example.im.infra.util.JsonUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

/**
 * @author PC
 * redis执行
 */
@Component
@ConditionalOnProperty(name = "cus.ws.communication-type", havingValue = "redis")
public class RedisSendExecutor extends AbstractBaseSendExecutor {

    private final static Logger logger = LoggerFactory.getLogger(RedisSendExecutor.class);

    private final static String CHANNEL_FOR_ALL = String.format("%s-all", webSocketProperties.getRedisChannelPrefix());

    private final static String CHANNEL_FOR_USER = String.format("%s-user", webSocketProperties.getRedisChannelPrefix());

    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    public void setRedisTemplate(RedisTemplate<String, String> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Override
    public String getCommunicationType() {
        return ImConstants.CommunicationType.REDIS;
    }

    @Override
    public void sendToUser(String sendUserName, String message) {
        MessageInfo messageInfo = new MessageInfo();
        messageInfo.setSendUserName(sendUserName);
        messageInfo.setMessage(message);
        messageInfo.setScopeOfSending(ScopeOfSendingEnum.USER);

        logger.debug("send to user redis websocket, channel is " + CHANNEL_FOR_USER);
        redisTemplate.convertAndSend(CHANNEL_FOR_USER, JsonUtils.toJson(messageInfo));
    }

    @Override
    public void sendToAll(String sendUserName, String message) {
        MessageInfo messageInfo = new MessageInfo();
        messageInfo.setSendUserName(sendUserName);
        messageInfo.setMessage(message);
        messageInfo.setScopeOfSending(ScopeOfSendingEnum.ALL);
        logger.debug("send to all redis websocket, channel is " + CHANNEL_FOR_ALL);
        redisTemplate.convertAndSend(CHANNEL_FOR_ALL, JsonUtils.toJson(messageInfo));
    }
}
